package com.chen.web;

import com.alibaba.fastjson.JSON;
import com.chen.dao.AddressDao;
import com.chen.dao.impl.AddressDaoImpl;
import com.chen.entity.Address;
import com.chen.entity.JSONBean;
import com.chen.util.UUIDUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/center/*")
public class MyCenterSrevlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String baseURL = request.getContextPath(); //获取项目基准路径
        String uri = request.getRequestURI();//截取项目二级路径
        String path = uri.substring(uri.lastIndexOf("/") + 1);
        JSONBean jsonBean = new JSONBean();
        AddressDao addressDao = new AddressDaoImpl();
        if("addressList.do".equals(path)){
            HttpSession session = request.getSession();
            String user_id = (String) session.getAttribute("user_id");
            List<Address> addressList = addressDao.findByUserId(user_id);
            request.setAttribute("addressList",addressList);
            request.getRequestDispatcher(baseURL+"/phone/gladdress.jsp").forward(request,response);
        }else if("addressForm.do".equals(path)){
            String consignee_name = request.getParameter("consignee_name");//获取收货人姓名
            String phone = request.getParameter("phone");//获取手机号
            String province = request.getParameter("province");//获取省份
            String town = request.getParameter("town");//获取市
            String county = request.getParameter("county");//获取县
            String detailAddress = request.getParameter("address");//获取详细地址
            String uuid = UUIDUtils.getUUID();//获取一个uuid作为地址的唯一id
            HttpSession session = request.getSession();
            String user_id = (String) session.getAttribute("user_id");
            Address address = new Address();
            address.setAddress_id(uuid);
            address.setConsignee_name(consignee_name);
            address.setUser_phone(phone);
            address.setProvince(province);
            address.setTown(town);
            address.setCounty(county);
            address.setAddress(detailAddress);
            address.setUser_id(user_id);
            int result = addressDao.save(address);
            if(result>0){
                jsonBean.setSuccess("添加新地址成功");
            }else{
                jsonBean.setFail("添加新地址失败");
            }
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter(); //获取输出
            String json = JSON.toJSONString(jsonBean);
            out.print(json);
            out.close();
        }
    }
}
